﻿using System;
using System.Data;
using Newtonsoft.Json;

namespace Syncronization.REST
{
    public class DataColumnConverter : JsonConverter
    {
        #region Fields

        private const string DataTypeProperty = "DataType";
        private const string NameProperty = "Name";

        #endregion

        #region public

        /// <summary>
        /// Determines whether this instance can convert the specified value type.
        /// </summary>
        /// <param name="valueType">Type of the value.</param>
        /// <returns>
        ///     <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanConvert(Type valueType)
        {
            return typeof (DataColumn).IsAssignableFrom(valueType);
        }

        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType)
        {
            var dataColumn = new DataColumn();

            reader.Read();
            while (reader.TokenType != JsonToken.EndObject)
            {
                if (reader.TokenType == JsonToken.PropertyName
                    && (string) reader.Value == NameProperty)
                {
                    reader.Read();
                    dataColumn.ColumnName = (string) reader.Value;
                }
                else if (reader.TokenType == JsonToken.PropertyName
                         && (string) reader.Value == DataTypeProperty)
                {
                    reader.Read();
                    dataColumn.DataType = Type.GetType((string) reader.Value);
                }
                reader.Read();
            }

            return dataColumn;
        }

        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        public override void WriteJson(JsonWriter writer, object value)
        {
            var dataColumn = value as DataColumn;

            writer.WriteStartObject();

            writer.WritePropertyName(NameProperty);
            writer.WriteValue(dataColumn.ColumnName);

            writer.WritePropertyName(DataTypeProperty);
            writer.WriteValue(dataColumn.DataType.FullName);

            writer.WriteEndObject();
        }

        #endregion
    }
}